//
//  YDCat.m
//  YDBASE
//
//  Created by rowena on 2019/9/20.
//  Copyright © 2019 wuyezhiguhun. All rights reserved.
//

#import "YDCat.h"
#import <objc/runtime.h>

@interface YDCat()

@property (nonatomic, strong) NSMutableDictionary *methodsMap;

@end

@implementation YDCat

+ (instancetype)shardCat {
    return [[self alloc] init];
}

/**
 * 手动实现init方法
 */
- (instancetype)init {
    
    _methodsMap = [NSMutableDictionary dictionary];
    [self registerMethodsWithTarget:[YDTiger new]];
    [self registerMethodsWithTarget:[YDLeopard new]];
    
    return self;
}

/**
 * 把要注册类的方法和类保存到字典中
 */
- (void)registerMethodsWithTarget:(id)target {
    unsigned int count = 0;
    Method *methodList = class_copyMethodList([target class], &count);
    for (int i = 0; i < count; i++) {
        Method method = methodList[i];
        SEL sel = method_getName(method);
        [_methodsMap setObject:target forKey:NSStringFromSelector(sel)];
    }
    free(methodList);
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
    NSString *methodName = NSStringFromSelector(sel);
    id target = _methodsMap[methodName];
    if (target && [target respondsToSelector:sel]) {
        return [NSMethodSignature signatureWithObjCTypes:"v@:"];
    } else {
        return [super methodSignatureForSelector:sel];
    }
}

- (void)forwardInvocation:(NSInvocation *)invocation {
    
    SEL sel = [invocation selector];
    NSString *methodName = NSStringFromSelector(sel);
    id target = _methodsMap[methodName];
    if (target && [target respondsToSelector:sel]) {
        [invocation invokeWithTarget:target];
    } else {
        [super forwardInvocation:invocation];
    }
}

@end
